<template>
  <div>
    <div class="node" v-has="{action: 'combo:list', effect: 'move'}">
    <div class="search_box topSelect">
      <!-- <SearchInput
        placeholder="套餐名称"
        label="套餐名称"
        style="margin-right:20px"
        :value="searchs.name"
        :onChange="(val) => changeSearch('name',val)"
        :onBlur="getQuery"
      /> -->
      <div class="selectBox">
        <label>活动类型:</label>
        <el-select
          v-model="searchs.type"
          clearable
          @change="getQuery"
          placeholder="请选择类型"
        >
          <el-option label="(直领)领券活动" :value="1"></el-option>
          <el-option label="等级活动" :value="2"></el-option>
          <el-option label="积分活动" :value="3"></el-option>
          <el-option label="vip活动" :value="4"></el-option>
          <el-option label="(vip会员日)领券活动" :value="5"></el-option>
        </el-select>
      </div>
      <div class="selectBox">
        <label>状态:</label>
        <el-select
          v-model="searchs.state"
          clearable
          @change="getQuery"
          placeholder="请选择状态"
        >
          <el-option label="待发布" :value="1"></el-option>
          <el-option label="已发布" :value="2"></el-option>
          <el-option label="已结束" :value="3"></el-option>
        </el-select>
      </div>
       <div class="searchBox1" style="margin-left: 20px">
         <el-button size="small" plain type="primary" icon="el-icon-search" @click="getQuery">查询</el-button>     
      </div>
    </div>
    <Panel title="营销活动" :intro="intro">
      <div slot='ext' class="examine">
        <el-button class="button-offt" v-has="{action: 'combo:add', effect: 'move'}" type="success" icon="el-icon-plus" @click="()=>editStore()">新增</el-button>
    </div>
    <TableEncapsulation
      slot="body"
      :tableConfig="tableConfig"
      :tableData="tableData"
    >
    <template slot="operation" slot-scope="operation">
          <el-button size="mini" icon="el-icon-edit"
            v-has="{action: 'combo:update', effect: 'move'}"
            @click="()=>editStore(operation.row, operation.row.state)"
          >{{operation.row.state==1? '编辑': '查看活动'}}</el-button>
          <!-- <el-link  
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.state ==1"
            type="danger"
            @click="()=>onLine(operation.row.id,'on')"
          >发布</el-link > -->
          <el-button size="mini" type="primary" icon="el-icon-s-promotion"
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.state ==1"
            @click="()=>onLine(operation.row.id,'on')"
          >发布</el-button>
          <el-button size="mini" type="danger" icon="el-icon-s-release"
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.state ==2"
            @click="()=>onLine(operation.row.id,'off')"
          >结束活动</el-button>
          <!-- <el-link 
           v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.state ==2"
            @click="()=>onLine(operation.row.id,'off')"
          type="danger">结束活动</el-link> -->
          <!-- <el-button
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.state ==2"
            type="text "
            class="danger"
            @click="()=>onLine(operation.row.id,'off')"
          >结束活动</el-button> -->
          <el-button size="mini"
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.type ==1 &&(operation.row.state ==1)"
            @click="()=>bandPost(operation.row)"
          >配置直领券</el-button>
          <el-button size="mini"
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.type ==2"
            @click="()=>bandPost(operation.row)"
          >配置等级</el-button>
          <el-button size="mini"
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.type ==3&&operation.row.state !==3"
            @click="()=>bandPost(operation.row)"
          >配置积分兑换券</el-button>
          <el-button size="mini"
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.type ==4"
            @click="()=>bandPost(operation.row)"
          >配置vip</el-button>
          <el-button size="mini"
            v-has="{action: 'combo:update', effect: 'move'}"
            v-if="operation.row.type ==5"
            @click="()=>bandPost(operation.row)"
          >配置会员日券</el-button>
          <!-- <el-button
            v-has="{action: 'user:combo:list', effect: 'move'}"
            type="text"
            @click="()=>commentDetail(operation.row.id)"
          >使用日志</el-button> -->
          <!-- <el-button
            v-has="{action: 'combo:delete', effect: 'move'}"
            type="text"
            @click="()=>remove(operation.row.id)"
          >删除</el-button> -->
        </template>
        <TablePager
          slot="pager"
          v-if="pager.use"
          :size="pager.size"
          :pageChange="pageChange"
          :show-total="pager.showTotal"
          :total="pager.total"
          :current="pager.current"
        >
          <span class="demonstration">GO></span>
        </TablePager>
    </TableEncapsulation>
    </Panel>
    <!-- 添加编辑 start-->
    <ModalPanel 
      :visible='visible'
      title="添加/编辑/查看"
      :onCancel="onCancel"
      class="bannerDialog"
      :showFooter='showUpdate'
      :onOk="onSubmit">
      <div>
        <ModifyForm
          :hiddenBtn='true'
          :editColumn='editColumn'
          :updateData="updateData"
          labelWidth='100px'
          ref="configModal"
          class="ModifyForm"
          :temporaryData='modalData'>
        <!-- 生效时间 -->
        <div slot="timeTamp">
          <el-date-picker
          v-model="appointmentTime"
          type="datetimerange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="timestamp"
          :picker-options="pickerOptions"
          style="height:40px"
        ></el-date-picker>
        </div>
        <!-- banner图 -->
        <div slot="bannerImage">
          <FileUpload class="ml10" @fileData="fileData" :config="ossConfig" number="1" :type="type" :imgae="bannerImg" />
        </div>
        <!-- 背景图 -->
        <div slot="backImgSlot">
          <FileUpload class="ml10" @fileData="fileDataBack" :config="ossConfig" number="1" :type="type" :imgae="backImg" />
        </div>
        <!-- 描述 -->
        <div slot="ruleSlot" style="margin-bottom:100px">
          <quill-editor 
                  v-model="rule" 
                  slot="body" ref="myQuillEditor" 
                  style="height: 300px" 
                  :options="editorOption">
                </quill-editor>
        </div>
        </ModifyForm>
      </div>
    </ModalPanel>
    <!-- 添加编辑end -->
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'combo:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import { objectFilter } from "@/tools/array";
import SearchInput from "@/components/SearchInput";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import { dateFormat } from "@/tools/time";
import FileUpload from '@/components/FileUpload/ossUpload';
export default {
  name: "comboList1",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
     ModalPanel,
    ModifyForm,
    FileUpload
  },
  data() {
    return {
      intro:{
        title: '',
        content: `营销活动`
      },
      tableData: [],
      searchs:{
        component: 'combo',
        name: '',
        type: '',
        state:'',
      },
       pager: {
        component: 'combo',
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      operation: true,
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      //添加编辑
      showUpdate: true,
      configValue:"",
      rule:'',
      editorOption: {},
      appointmentTime:null,
      appointmentTimePost: null,
      myQuillEditor:'',
      typeList: [],
      timed:{
          name: "生效时间",
          prop: "time",
          type: "other",
          width:24,
          required: false,
          slotName: 'timeTamp',
          desc: '生效类型为指定时间时，此项为必填'
        },
      visible:false,
      modalData:{},
      // 图片
      backImg: [],
      ossConfig: {},
      bannerImg:[],
      type: ['jpg','png', 'gif', 'jpeg'],
      editColumn: [
        {
          name: "类型",
          prop: "type",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择类型"},{'id': 1,'name': "(直领)领券活动"},{'id':2, 'name':"等级活动"},{'id':3, 'name':"积分活动"},{'id':4, 'name':"vip活动"},{'id':5, 'name':"(vip会员日)领券活动"}],
          onChange: (val) => {
            if(val==5){
              this.editColumn[4].hidden = false
            }else{
              this.editColumn[4].hidden = true
            }
          },
          width:24,
          required: true
        },
        {
          name: "活动标题",
          prop: "title",
          type: "text",
          width:24,
          required: true
        },
        {
          name: "仅vip用户参与",
          prop: "vip",
          type: "radio",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': false,'name': "否"},{'id':true, 'name':"是"}],
          onChange: (val) => {
          },
          width:24,
          required: true
        },
        {
          name: "首页轮播显示",
          prop: "canShow",
          type: "radio",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': false,'name': "不可见"},{'id':true, 'name':"可见"}],
          onChange: (val) => {
          },
          width:24,
          required: true
        },
        {
          name: "周几有效",
          prop: "weekOfTime",
          type: "number",
          width:24,
          hidden: true,
          // required: true
        },
        // {
        //   name: "状态",
        //   prop: "state",
        //   type: "radio",
        //   optionBindLabel: 'name',
        //   optionBindValue: 'id',
        //   optionList: [{'id': 1,'name': "待发布"},{'id':2, 'name':"已发布"}],
        //   onChange: (val) => {
        //   },
        //   width:24,
        //   required: true
        // },
        {
          name: "活动时间",
          prop: "time",
          type: "other",
          width:24,
          required: false,
          slotName: 'timeTamp',
          desc: '可参与活动时间周期，必填'
        },
        
        {
          name: "跳转路由",
          width: 24,
          prop: "route",
          type: "text",
          required: false
        },
        {
          name: "背景图",
          width: 24,
          prop: "image",
          type: "other",
          required: false,
          slotName: "backImgSlot"
        },
        {
          name: "轮播图",
          width: 24,
          prop: "image",
          type: "other",
          required: false,
          slotName: "bannerImage"
        },
        {
          name: "规则说明",
          width: 24,
          prop: "rule",
          type: "textarea",
          required: false,
          // slotName: 'ruleSlot'
        },
        // {
        //   name: "套餐描述",
        //   width: 24,
        //   prop: "desc",
        //   type: "other",
        //   required: false,
        //   slotName: 'ruleSlot'
        // },
      ],
      //添加编辑end
    };
  },
  mounted() {
    // this.searchsFnc()
    this.getQuery();
    this.getOssToken()
  },
  computed: {
    tableConfig () {
      return {
        selection: false,
        columnConfig: [
          {
            label: "编号",
            type: "text",
            prop: "id",
            align: "center"
          },
          {
            label: "活动标题",
            type: "text",
            prop: "title",
            align: "center"
          },
          {
            label: "发放优惠券数量",
            type: "text",
            prop: "releaseNums",
            align: "center"
          },
          {
            label: "仅vip用户参与",
            type: "other",
            prop: "vip",
            align: "center",
            fnc: val => val == 1 ? '是': '否',
            class:  val => val == 1 ? "agree" :  "denger-tag" ,

          },
          {
            label: "客户端状态",
            type: "other",
            prop: "canShow",
            align: "center",
            fnc: val => val == 1 ? '可见': '不可见',
            class:  val => val == 1 ? "agree" :  "denger-tag" ,
          },
          
          {
            label: "类型",
            type: "other",
            prop: "type",
            align: "center",
            fnc: val => val == 1 ? '(直领)领券活动': val ==2 ? '等级活动': val ==3 ? '积分活动': val ==4 ? 'vip活动': val ==5 ? '(vip会员日)领券活动':  '未知'
          },
          {
            label: "周几有效",
            type: "text",
            prop: "weekOfTime",
            align: "center"
          },
          {
            label: "活动时间",
            type: "text",
            prop: "times",
            align: "center",
            width: 166
          },
          {
            label: "跳转路由",
            type: "text",
            prop: "route",
            align: "center"
          },
          {
            label: "背景图",
            type: "text",
            prop: "bgImgUrl",
            align: "center",
            overflow: true,
          },
          {
            label: "轮播图",
            type: "text",
            prop: "bannerImgUrl",
            align: "center",
            overflow: true,
          },
          {
            label: "状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 2 ? '已发布':val == 1 ? '待发布' :'已结束',
            class:  val => val == 2 ? "agree" :val == 1 ? "wait" :  "cancel" ,
          },
          {
            label: "规则说明",
            type: "text",
            prop: "rule",
            align: "center",
            overflow: true,
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
   async getOssToken(){
      let { info } = await request({
        url: "/oss/auth/oss/token",
        method: "GET",
        data: {}
      });
      this.ossConfig = info
    },
    choose(val){
      console.log('ssssssssss',val)
    },
    
    async getQuery() {
      let state =  this.searchs.state
      let type = this.searchs.type
      let name = this.searchs.name
      let page = this.pager.current
      const res = await request({
       url: `/client/event/list?type=${type}&state=${state}&page=${page}&size=10`,
        method: "GET",
      });
      let data = res.page.list
      data.map(item =>{
        item.times = item.startTime+'至'+item.endTime
        return item
      })
      this.tableData = data
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getQuery();
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    
    commentDetail(id){
      this.$store.commit('saveSearchs', this.searchs)
      this.$store.commit('savePager', this.pager)
      this.$router.push({ path: "/combo/details",query:{couponId:id,type: "toview"} })
    },
    // 
    bandPost(row){
      if(row.type==1){
        this.$router.push({ path: "/combo/vip/band",query:{eventId:row.id,eventTitle: row.title} })
      }else if(row.type ==2){
        this.$router.push({ path: "/wx/user/leval",query:{eventId:row.id,eventTitle: row.title} })
      }else if(row.type ==3){
        this.$router.push({ path: "/combo/score/band",query:{eventId:row.id,eventTitle: row.title} })
      }else if(row.type ==4){
        this.$router.push({ path: "/combo/vip/index",query:{eventId:row.id,eventTitle: row.title} })
      }else if(row.type ==5){
        this.$router.push({ path: "/combo/vip/band",query:{eventId:row.id,eventTitle: row.title} })
      }
    },
    // 发布
    async onLine(id,type){
      let url , msg
      if(type=='off'){
        url = `/client/event/offline/${id}`
        msg = '下线成功'
     }else{
        url = `/client/event/effect/${id}`
        msg = '上线成功'
     }
      let res = await request({
        url: url,
        method: "POST",
      });
      if(res.code !==0 ) return
      this.$message.success(msg)
      this.getQuery()
    },

     //添加编辑start
    editStore(rowData, state){
      if(rowData){
        if(rowData.type ==5){
          this.editColumn[4].hidden =false
        }else{
          this.editColumn[4].hidden =true
        }
        this.modalData = {...rowData}
        this.backImg = [rowData.bgImgUrl]
        this.bannerImg = [rowData.bannerImgUrl]
        this.appointmentTime = [new Date(rowData.startTime).getTime(), new Date(rowData.endTime).getTime() - 86400000+1000]
      }else{
        this.modalData ={}
        this.appointmentTime =[]
        this.appointmentTimePost = []
      }
      if(!state || state==1){
        this.showUpdate = true
      }else{
        this.showUpdate = false
      }
      this.visible = true
    },
    fileData(data){
      this.bannerImg = data
    },
    fileDataBack(data){
      this.backImg = data
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    onCancel(){
      this.visible = false
    },
    async updateData(values){
      if (this.appointmentTime.length<1) return this.$message.error('请输入活动时间')
      let bgImgUrl = this.backImg[0]
      let bannerImgUrl = this.bannerImg[0]
      // let bgImgUrl = '1'
      // let bannerImgUrl = '1'
      // let rule = this.rule
     let startTime  = dateFormat(this.appointmentTime[0] ? this.appointmentTime[0] : undefined, 'yyyy-MM-dd HH:mm:ss')
     let endTime  = dateFormat(this.appointmentTime[1] ? (this.appointmentTime[1] + 86400000-1000) : undefined, 'yyyy-MM-dd HH:mm:ss')
     const { id, title,  vip,  type, weekOfTime, canShow, route, rule} = values
     if(canShow && !bannerImgUrl){
      this.$message.error('客户端可见必须上传轮播图图片')
      return
     }
     var post = objectFilter({startTime,endTime,rule, id, title,  vip,  type, weekOfTime, canShow, route, bgImgUrl,bannerImgUrl, rule})
     console.log('post',post)
    //  return
     let url = id ? "/client/event/update": "/client/event/add"
     let msg = id ? "编辑成功" : "添加成功"
     let res = await request({
       url: url,
       method: "POST",
       data:post
     })
     if(res.code !==0) return
      this.$message.success(msg)
      this.visible = false
      this.getQuery();
    },
    //添加编辑end
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        let del = await request({
        url: "/combo/delete",
        method: "POST",
        dataType: 'json',
        data:  [id]
      });
      if (del.code !==0) return
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getQuery()
      })
    },
  }
}
</script>
<style lang='scss' module>
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}

</style>